using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Permissions;

namespace Team.API.Applocation.Handler.Users.Permissions
{
    /// <summary>
    /// 查询权限处理器
    /// </summary>
    public class QueryPermissionHandler : IRequestHandler<QueryPermissionCommand, APIPaging<PermissionDTO>>
    {
        private readonly IRepository<Permissionmodel> permissionRepository;

        public QueryPermissionHandler(IRepository<Permissionmodel> permissionRepository)
        {
            this.permissionRepository = permissionRepository;
        }

        public async Task<APIPaging<PermissionDTO>> Handle(QueryPermissionCommand request, CancellationToken cancellationToken)
        {
            int pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
            int pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

            var query = permissionRepository.GetAll()
                .Where(p => p.IsDel == false)
                .WhereIF(!string.IsNullOrWhiteSpace(request.PermissionName),
                    p => p.PermissionName.Contains(request.PermissionName!.Trim()))
                .WhereIF(request.ParentId.HasValue, p => p.ParentId == request.ParentId!.Value)
                .WhereIF(request.PermissionType.HasValue, p => p.PermissionType == request.PermissionType!.Value)
                .WhereIF(request.Status.HasValue, p => p.Status == request.Status!.Value)
                .OrderBy(p => p.Sort)
                .OrderBy(p => p.Id, OrderByType.Desc)
                .Select(p => new PermissionDTO
                {
                    Id = p.Id,
                    PermissionCode = p.PermissionCode,
                    PermissionName = p.PermissionName,
                    PermissionUrl = p.PermissionUrl,
                    ParentId = p.ParentId,
                    PermissionType = p.PermissionType,
                    Icon = p.Icon,
                    Sort = p.Sort,
                    Status = p.Status,
                    Description = p.Description,
                    Remark = p.Remark
                });

            int totalCount = 0;
            var result = query.ToPageList(pageIndex, pageSize, ref totalCount);

            return new APIPaging<PermissionDTO>
            {
                Totalcount = totalCount,
                Code = StateCode.OK,
                Message = "获取权限列表成功",
                ListResult = result
            };
        }
    }
}
